<template>
  <div class="page-container relative">
    <BaseCollapse title="基础信息">
      <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="baseRef" />
    </BaseCollapse>
    <BaseCollapse title="归档文件信息">
      <div>
        <div v-if="['ADD', 'EDIT'].includes(state.showType)" class="space-x-2">
          <a-button type="primary" @click="handleImport">
            <template #icon><ImportOutlined /></template>导入清单
          </a-button>
          <a-button @click="handleAttImport">
            <template #icon><FileOutlined /></template>批量上传附件
          </a-button>
          <a-button @click="handleDelete">
            <template #icon><DeleteOutlined /></template>删除
          </a-button>
        </div>
        <a-button v-if="['ADD', 'EDIT'].includes(state.showType)" class="w-full my-4" type="dashed" @click="handleModalAdd">
          <template #icon><PlusOutlined /></template>添加
        </a-button>
        <ModalCollapse
          v-for="(item, index) in filterList"
          v-model:checked="item.checked"
          :key="state.modalList.length - ((state.pageVo.currentPage - 1) * state.pageVo.pageSize + index)"
          :index="state.modalList.length - ((state.pageVo.currentPage - 1) * state.pageVo.pageSize + index)"
          :closable="['ADD', 'EDIT'].includes(state.showType)"
          @close="handelModalClose(state.modalList.length - ((state.pageVo.currentPage - 1) * state.pageVo.pageSize + index))"
        >
          <ModalForm v-model:data="item.data" :show-type="state.showType" :is-force="item.isForce" ref="modalFormRef" />
        </ModalCollapse>
        <!-- 数据只有一条，取消分页 -->
        <div class="flex justify-end" v-if="!(state.modalList.length == 1 && state.showType == 'VIEW')">
          <a-pagination
            v-model:current="state.pageVo.currentPage"
            v-model:pageSize="state.pageVo.pageSize"
            :pageSizeOptions="state.pageVo.pageSizeOptions"
            show-quick-jumper
            show-size-changer
            :total="state.modalList.length"
            :show-total="(total) => `共 ${total} 条`"
            @change="onPageChange"
          />
        </div>
      </div>
    </BaseCollapse>
    <BaseCollapse title="归档信息">
      <DynamicForm :config="dyCreatorConfig" :questions="dyCreatorQuestions" ref="creatorRef" />
    </BaseCollapse>
    <BaseCollapse v-if="['VIEW'].includes(state.showType)" title="档案存档录入">
      <DynamicTable :tables="dyEnterTable" :config="dyEnterTableConfig" />
    </BaseCollapse>
    <ApprovalDetail v-if="['VIEW', 'AUDIT', 'RECEIVE'].includes(state.showType) && query.processInstanceId" :config="approvalConfig" @back="approvalGoBack"></ApprovalDetail>
    <div class="space-x-2 w-full text-center my-4">
      <a-button v-if="!['RECEIVE', 'AUDIT'].includes(state.showType)" @click="cancel">返回</a-button>
      <a-button v-if="['ADD', 'EDIT'].includes(state.showType)" @click="submit(0)">暂存</a-button>
      <a-button v-if="['ADD', 'RECEIVE', 'EDIT'].includes(state.showType)" type="primary" @click="submit(1)">提交</a-button>
      <a-button v-if="['VIEW'].includes(state.showType) && [1, 3].includes(state.archiveStatus)" type="primary" @click="handleEdit">编辑</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { createVNode, getCurrentInstance, onBeforeUnmount, onMounted, reactive, nextTick, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import AuditRecord from '@/components/common/AuditRecord/index.vue';
import ApprovalDetail from '@/components/approval-details/index.vue';
import indexService from './index.service';
import ModalCollapse from './components/modalCollapse.vue';
import ModalForm from './components/modalForm.vue';
import { fileAudit, fileAuto, fileGet, fileReceive, fileSave } from '@/config/api/archivesFile';
import { message, Modal } from 'ant-design-vue';
import { DYNAMICLAYERCLEAR, DYNAMICLAYERUPLOAD, DYNAMICLOCALTABLE } from '@/mixins/subject/subject-types';
import { Api } from '@/config/api/archivesFile';
import { Api as ApiResource } from '@/config/api/resourceFileInfo';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { filter } from 'rxjs/operators';
import { downloadFile } from '@/utils/useDownload';
import { throttle } from 'xe-utils';

const { query } = useRoute();

const state = reactive({
  showType: 'ADD', // enum 'ADD' 'VIEW' 'AUDIT' 'RECEIVE'
  archiveStatus: null, // 档案状态
  modalList: [],
  pageVo: {
    pageSize: 10,
    currentPage: 1,
    pageSizeOptions: ['10', '25', '50', '100']
  }
});
const baseRef = ref(null);
const modalFormRef = ref(null);
const creatorRef = ref(null);
const receiveRef = ref(null);
const commentRef = ref(null);

const approvalConfig: any = ref({
  title: '审批流程',
  showBackBtn: true, //显示返回按钮
  showAgreeBtn: true, //显示同意按钮
  showGoBackBtn: true, // 显示退回按钮
  showRejectBtn: true // 显示拒绝按钮
});

const approvalGoBack = (cb: any) => {
  cb?.();
};
const dyConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const dyCreatorConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const dyCommentConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const dyTableConfig: any = reactive({
  name: 'receiveTable'
});
const route = useRoute();
const router = useRouter();
const dyEnterTableConfig: any = {
  name: 'enterTable',
  queryUrl: Api.fileInfoPage,
  protType: 'post',
  params: {
    billId: route.query.id,
    isWaitInput: false
  },
  scroll: { x: 2100 }
};
const { proxy }: any = getCurrentInstance();
state.showType = route.query.showType as string;
// const formStore = formInfoStore();
// formStore.setQuestions(state.showType == 'ADD' ? indexService.getModalQuestions() : indexService.getViewModalQuestions());
const dyQuestions: any = reactive(indexService.getQuestions());
const dyCreatorQuestions: any = reactive(['ADD', 'EDIT'].includes(state.showType) ? indexService.getCreatorQuestions() : indexService.getViewCreatorQuestions());
const dyCommentQuestions: any = reactive(indexService.getCommentQuestions({ showType: state.showType }));
const dyTable: any = reactive(indexService.getTables({ showType: state.showType }));
const dyIcons: any = reactive(indexService.getIcons({ showType: state.showType, handleReceiveImport }));
const dyEnterTable: any = reactive(indexService.getEnterTables());
const filterList = computed(() => {
  const current = state.pageVo.currentPage;
  const size = state.pageVo.pageSize;
  return state.modalList.slice((current - 1) * size, current * size);
});

onMounted(() => {
  if (state.showType == 'ADD') {
    fileAuto().then((result) => {
      if (result.success) {
        // 基本信息
        const data = result.data;
        dyQuestions.forEach((item) => (item.value = data[item.key]));
      }
    });
    state.modalList.push({
      checked: true,
      data: {}
    });
  } else if (['AUDIT', 'RECEIVE', 'VIEW', 'EDIT'].includes(state.showType)) {
    fileGet(route.query.id).then((result) => {
      if (result.success) {
        // 基本信息
        const data = result.data;
        state.archiveStatus = result.data.status;
        dyQuestions.forEach((item) => (item.value = data[item.key]));
        // 归档文件信息
        const fileList = result.data.fileList;
        for (let i = 0; i < fileList.length; i++) {
          state.modalList.push({
            checked: true,
            data: fileList[i]
          });
        }
        // 归档接收确认
        if (receiveRef.value) receiveRef.value.dataList.value = data.archivesFileConfirmAttachmentList;
        // 归档信息
        dyCreatorQuestions.forEach((item) => (item.value = data[item.key]));
      }
    });
  }
  if (['VIEW'].includes(state.showType)) {
    approvalConfig.value.showBackBtn = false;
    approvalConfig.value.showAgreeBtn = false;
    approvalConfig.value.showGoBackBtn = false;
    approvalConfig.value.showRejectBtn = false;
  }
});
// 监听table
const subscribeSub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === DYNAMICLOCALTABLE) {
      if (item.value.part.state?.type == 'delete') {
        Modal.confirm({
          title: '是否确认删除？',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            receiveRef.value.dataList.value = receiveRef.value.dataList.value.filter((itemTable) => itemTable.id !== item.value.data.id);
          },
          onCancel() {}
        });
      } else if (item.value.part.state?.type == 'download') {
        const url = `${ApiResource.resourceViewFile}/${item.value.data.id}`;
        downloadFile(url);
      } else if (item.value.part?.type == 'local') {
        console.log('aa', item);
        previewFile(item);
      }
    }
  });

function cancel() {
  router.go(-1);
}
//预览文件地址
function previewFile(file) {
  const params = { id: file.value.data.id, expires: 2, timeUnit: 'HOURS' };
  proxy.$Http.api(ApiResource.getPreviewFileUrl, params, 'post').then((data: any) => {
    if (data.success && data.data) {
      let a = document.createElement('a');
      a.href = data.data;
      a.target = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  });
}
// 提交 op操作（0=暂存；1=提交）
const submit = throttle(async function (op) {
  if (['ADD', 'EDIT'].includes(state.showType)) {
    // 基本信息
    const baseData = baseRef.value.getDataFrom();
    // 归档文件信息
    let isError;
    for (let i = 0; i < modalFormRef.value.length; i++) {
      // 校验已选项
      if (state.modalList[i].checked) {
        // 当暂存时，不校验
        await modalFormRef.value[i].isValidateFields(op == 0 ? [] : null).catch((error) => {
          console.warn(error);
          isError = true;
        });
      }
    }
    const fileList = state.modalList.filter((item) => item.checked).map((item) => item.data);
    // 归档信息
    await creatorRef.value.isValidateFields(op == 0 ? [] : null).catch((error) => {
      isError = true;
      console.warn(error);
    });
    const creatorData = creatorRef.value.getDataFrom();
    const params = {
      op,
      ...baseData,
      ...creatorData,
      fileList
    };
    state.showType == 'EDIT' && Object.assign(params, { id: route.query.id });
    if (isError) return;
    fileSave(params).then((result) => {
      if (result.success) {
        message.success(op === 1 ? '提交成功' : '保存成功');
        router.go(-1);
      }
    });
  } else if (state.showType == 'AUDIT') {
    const commentData = commentRef.value.getDataFrom();
    const params = {
      billId: route.query.id,
      ...commentData
    };
    fileAudit(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  } else if (state.showType == 'RECEIVE') {
    const commentData = commentRef.value.getDataFrom();
    const params = {
      id: route.query.id,
      archivesFileConfirmAttachmentList: receiveRef.value.dataList.value,
      ...commentData
    };
    fileReceive(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  }
}, 3000);
// 编辑
function handleEdit() {
  router
    .replace({
      name: 'ArchivesManageAddFile',
      query: {
        id: route.query.id,
        showType: 'EDIT'
      }
    })
    .then(() => {
      router.go(0);
    });
}
// 归档文件窗口添加
function handleModalAdd() {
  state.modalList.unshift({
    checked: true,
    data: {}
  });
  // 返回第一页
  if (state.modalList.length > state.pageVo.pageSize) state.pageVo.currentPage = 1;
}
// 归档文件窗口关闭
function handelModalClose(index) {
  Modal.confirm({
    title: '是否确认删除？',
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确定',
    cancelText: '取消',
    onOk() {
      state.modalList.splice(state.modalList.length - index, 1);
      // 删除最后一条时页数减一
      if (filterList.value.length == 0 && state.pageVo.currentPage !== 1) {
        state.pageVo.currentPage -= 1;
      }
    },
    onCancel() {}
  });
}
// 分页
function onPageChange(pageNumber, pageSize) {
  state.pageVo.currentPage = pageNumber;
  state.pageVo.pageSize = pageSize;
}
// 导入文件信息
function handleImport() {
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERUPLOAD,
    value: {
      state: {
        url: Api.fileInfoImport,
        downloadUrl: Api.fileGetImportTemplate,
        downloadProtType: 'post',
        downloadParams: { templateCode: 'archives_apply' },
        downloadHeader: true,
        downloadName: '下载导入模板',
        downloadFileName: '档案文件归档清单',
        downloadRule: '支持Word、PPT、Excel、PDF、txt、FASTA、XML、视频、音频、照片、等文件格式，',
        hideMessage: true,
        multiple: false,
        callback: (data) => {
          parseImportData(data);
        }
      }
    }
  });
}
// 导入附件
function handleAttImport() {
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERUPLOAD,
    value: {
      state: {
        url: ApiResource.resourceUploadFiles,
        downloadRule: '支持扩展名：.rar .zip .doc .docx .pdf .jpg...',
        hideMessage: true,
        splitRequest: true,
        // downloadUrl: true,
        autoUploadFileServer: false,
        multiple: true,
        maxCount: 50,
        httpOpt: { timeout: 1000 * 60 * 3 }, // 接口超时时间3min
        // beforeWithMethod: (data) => {
        //   proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR });
        // },
        callback: (data) => {
          parseImportAttData(data);
        }
      }
    }
  });
}
// 删除文件信息
function handleDelete() {
  if (state.modalList.some((item) => item.checked)) {
    Modal.confirm({
      title: '是否确认删除？',
      icon: createVNode(ExclamationCircleOutlined),
      okText: '确定',
      cancelText: '取消',
      onOk() {
        state.modalList = state.modalList.filter((item) => !item.checked);
        message.success('删除成功');
        if (filterList.value.length == 0 && state.pageVo.currentPage !== 1) {
          state.pageVo.currentPage -= 1;
        }
      },
      onCancel() {}
    });
  } else {
    message.warning('请先选中一个选项');
  }
}
// 解析文件信息
function parseImportData(result) {
  if (result.message.length > 0) {
    message.warning({
      content: result.message.join('\n\u00A0\u00A0\u00A0\u00A0'),
      duration: 6,
      style: {
        whiteSpace: 'pre-line' // 支持换行样式
      }
    });
  } else {
    message.success('上传成功！');
  }
  if (result.list.length > 0) {
    // 初次添加判断名称和档案编码未填写则覆盖
    if (state.modalList.length == 1 && !state.modalList[0].data.name && !state.modalList[0].data.filesBoxCode) state.modalList = [];
    nextTick(() => {
      for (let i = 0; i < result.list.length; i++) {
        state.modalList.unshift({
          checked: true,
          data: result.list[i],
          isForce: true // 强添加
        });
      }
    });
  }
}
// 解析附件
function parseImportAttData(list) {
  // 处理后端返回数据格式
  list = list.map((item) => {
    return item[0] && item[0];
  });
  const nameList = list.map((item) => item.name.substring(0, item.name.lastIndexOf('.') == -1 ? item.name.length : item.name.lastIndexOf('.')).trim());
  // 按顺序分配附件
  const modalList = state.modalList.slice().reverse();
  const wranList = [];
  const modalNameList = state.modalList.reduce((total, item) => {
    if (item.data.name) total.push(item.data.name.trim());
    if (item.data.filesBoxCode) total.push(item.data.filesBoxCode.trim());
    return total;
  }, []);
  for (let i = 0; i < modalList.length; i++) {
    // 根据文件名称，档案编码分配附件
    for (let j = 0; j < list.length; j++) {
      const fileName = list[j].name.substring(0, list[j].name.lastIndexOf('.') == -1 ? list[j].name.length : list[j].name.lastIndexOf('.')).trim();
      const name = modalList[i].data.name && modalList[i].data.name.trim();
      const filesBoxCode = modalList[i].data.filesBoxCode && modalList[i].data.filesBoxCode.trim();
      if ([name, filesBoxCode].includes(fileName)) {
        // 有文件名称
        setData(modalList[i], list[j]);
      } else if (!modalList[i].data.name && !modalNameList.includes(fileName)) {
        // 无文件名称
        list[i] && setData(modalList[i], list[i]);
      }
    }
    if (modalList[i].data.name && !nameList.includes(modalList[i].data.name.trim())) {
      wranList.push(modalList[i].data.name);
    }
  }
  if (wranList.length > 0) {
    message.warning({
      content: `【${wranList.join('，')}】未匹配到文件列表数据行，导入失败`,
      duration: 6
    });
  } else {
    message.success('上传成功！');
  }
  function setData(target, data) {
    target.data.attachment = {
      fileId: data.id,
      name: data.name,
      size: data.size,
      suffix: data.suffix
    };
  }
}
// 归档接收确认导入
function handleReceiveImport(result) {
  if (Array.isArray(result)) {
    receiveRef.value.dataList.value.push(...result);
  } else {
    receiveRef.value.dataList.value.push(result);
  }
}
onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped></style>
